package com.samsung.sbackup;

import java.io.File;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.samsung.adapter.AppsAdapter;

public class TabBackupedApps extends Fragment {

	ListView lvApps;
	Button btnBackup;
	AppsAdapter adapter;
	SparseArray<Drawable> hashMapIcon;
	SparseArray<String> hashMapName;
	SharedPreferences sharedPref;
	ArrayList<ApplicationInfo> appsList;
	boolean isCheckedAll;
	boolean loadFinised;
	ArrayList<ApplicationInfo> backupedApps;
	Button btnRestore;
	String folder;

	public TabBackupedApps() {
		hashMapIcon = new SparseArray<Drawable>();
		hashMapName = new SparseArray<String>();
		setHasOptionsMenu(true);
		isCheckedAll = false;
		loadFinised = false;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.tab_backuped_apps, null);

		sharedPref = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		folder = sharedPref.getString(FragmentSettingsPreference.BACKUP_PATH,
				"/") + "/" + "app";
		lvApps = (ListView) view.findViewById(R.id.tab_backuped_apps_listview);
		btnRestore = (Button) view
				.findViewById(R.id.tab_backuped_apps_btnRestore);

		lvApps.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				arg1.setBackgroundColor(getResources().getColor(
						android.R.color.holo_blue_light));
				adapter.getCheckedItems()[arg2] = !adapter.getCheckedItems()[arg2];
				adapter.notifyDataSetChanged();
			}

		});

		btnRestore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayList<ApplicationInfo> selectedItems = adapter
						.getSelectedItems();
				for (ApplicationInfo app : selectedItems) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(
							Uri.fromFile(new File(folder
									+ "/"
									+ app.loadLabel(getActivity()
											.getPackageManager()) + ".apk")),
							"application/vnd.android.package-archive");
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
			}
		});

		new LoadTask().execute();

		return view;
	}

	public class LoadTask extends AsyncTask<Void, Void, String> {

		ProgressDialog progressDialog;
		String returnString;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			returnString = "";
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage("Loading applications...");
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			backupedApps = new ArrayList<ApplicationInfo>();
			hashMapIcon = new SparseArray<Drawable>();
			hashMapName = new SparseArray<String>();
			File filesApk = new File(folder);
			if (!filesApk.exists())
				filesApk.mkdirs();
			File[] apks = filesApk.listFiles();
			if (apks != null && apks.length != 0) {
				for (int i = 0; i < apks.length; i++) {
					if (apks[i].getPath().endsWith(".apk")) {
						PackageInfo packageInfo = getActivity()
								.getPackageManager().getPackageArchiveInfo(
										apks[i].getPath(),
										PackageManager.GET_ACTIVITIES);
						if (packageInfo != null) {
							ApplicationInfo appInfo = packageInfo.applicationInfo;
							if (Build.VERSION.SDK_INT >= 8) {
								appInfo.sourceDir = apks[i].getPath();
								appInfo.publicSourceDir = apks[i].getPath();
							}
							backupedApps.add(appInfo);
							hashMapName.put(
									i,
									appInfo.loadLabel(
											getActivity().getPackageManager())
											.toString());
							hashMapIcon.put(i, appInfo.loadIcon(getActivity()
									.getPackageManager()));
						}
					}
				}
			}

			if (apks == null)
				System.out.println("Apps backup folder is invalid");
			else if (apks.length == 0)
				returnString = "None";
			else
				returnString = String.valueOf(apks.length) + " apps found";
			return returnString;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			adapter = new AppsAdapter(getActivity(), backupedApps,
					R.layout.app_item, hashMapIcon, hashMapName, null);
			lvApps.setAdapter(adapter);
			loadFinised = true;
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.apps_backup, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.apps_backup_select_all && loadFinised) {
			if (!isCheckedAll) {
				boolean[] checkItems = adapter.getCheckedItems();
				for (int i = 0; i < checkItems.length; i++) {
					checkItems[i] = true;
				}
				adapter.setCheckedItems(checkItems);
				isCheckedAll = true;
			} else {
				boolean[] checkItems = adapter.getCheckedItems();
				for (int i = 0; i < checkItems.length; i++) {
					checkItems[i] = false;
				}
				adapter.setCheckedItems(checkItems);
				isCheckedAll = false;
			}
		}

		return super.onOptionsItemSelected(item);
	}
}
